#shaiya 3DC parser
import os
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class shaiya3DC_Object(Model3D):
    
   def __init__(self, obj3D=None, inFile=None, outFile=None):
      '''Initialize a shaiya 3DC Object.'''
      
      super(shaiya3DC_Object, self).__init__("3DC")
      self.obj3D = obj3D
      self.inFile = inFile
      self.outFile = outFile
      
   def parse_material(self, filename):
      
      self.create_material(0)
      self.add_material_name(0, filename)
      self.add_texture_name(0, filename + ".png")

   def parse_file(self, objName):
      
      self.create_object(objName)
      
      self.inFile.read(4)
      boneCount = self.inFile.read_long()
      print "%d bones" %boneCount
      
      for i in range(0, boneCount):
         bones = self.inFile.read_float(16)
      
      vertCount = self.inFile.read_long()
      print "%d vertices " %vertCount
      for i in range(0, vertCount):
         vx, vy, vz = self.inFile.read_float(3)
         weight = self.inFile.read_float()
         bone1, bone2, null1, null2 = self.inFile.read_char(4)
         nx, ny, nz = self.inFile.read_float(3)
         tu, tv = self.inFile.read_float(2)
         
         vx = float(vx) * -1
         self.create_vertex(objName, i)
         self.add_coords(objName, i, [vx, vy, vz])
         self.add_vert_uv(objName, i, [round(tu, 6), round(tv, 6)])
         self.add_vert_normals(objName, i, [nx, ny, nz])
          
      faceCount = self.inFile.read_long()
      print "%d faces" %faceCount
      for i in range(0, faceCount):
         f1, f2, f3 = self.inFile.read_short(3)
         
         self.create_face(objName, i)
         self.add_face_verts(objName, i, [f1, f2, f3])
         self.add_face_material(objName, i, 0)
            
def read_file(path):
   
   openFile = StructReader(open(path, 'rb'))
   filename, ext = os.path.splitext(os.path.basename(path))
   obj = shaiya3DC_Object(inFile=openFile)
   obj.parse_material(filename)
   obj.parse_file(filename)
   openFile.close()
   return obj

def write_file():
   
   pass

def definitions():
   
   return "", "3DC", "Shaiya3DC"
             
if __name__ == '__main__':
              
   filename = "NPC_strip_f_01_A.3DC"
   obj = read_3DC(filename)